package com.yanze.controller;

import com.yanze.pojo.TestUser;
import com.yanze.utils.BaseJSONResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//@RestController
@Controller
public class TestUpdataImg {
    //    public static final String headerPath = "A:\\SchoolInformationImg\\Header\\";
    private static final String IMG_PATH = "A:\\SchoolInformationImg\\";
    public static final String IMG_HEADER = IMG_PATH + "\\Header\\";
    public static final String IMG_FRIEND = IMG_PATH + "\\Friend\\";
    public static final String IMG_BOOK = IMG_PATH + "\\Book\\";

    /**
     * 网址路径中的请求
     *
     * @PathVariable 注解可以获取网址中占位的参数
     * 如果方法中参数名不一致：@PathVariable("account") String phoneNumber，account要与路径中占位变量一致
     * 注意：路径中不能有中文
     */
    @RequestMapping(path = "/{name}/{describe}/getUser", method = RequestMethod.GET)
    @ResponseBody
    public BaseJSONResult getUser(@PathVariable String name, @PathVariable String describe) {
        TestUser user = new TestUser();
        user.setName(name);
        user.setDecribe(describe);
        return BaseJSONResult.ok(user);
    }

    /**
     * 带请求参数的请求
     *
     * @RequestParam 获取请求参数
     */
    @RequestMapping(path = "/getAccount", method = RequestMethod.POST)
    @ResponseBody
    public BaseJSONResult getAccount(@RequestParam String name, @RequestParam String describe) {
        TestUser user = new TestUser();
        user.setName(name);
        user.setDecribe(describe);
        return BaseJSONResult.ok(user);
    }

    /**
     * 带请求体的请求
     *
     * @RequestBody 将请求体解析到对应实体类中
     * @PostMapping(path = "/register") = @RequestMapping(path = "/register",method = RequestMethod.POST)
     * @GetMapping = @RequestMapping(method = RequestMethod.GET)
     * @PutMapping = @RequestMapping(method = RequestMethod.PUT)
     * @DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)
     */
    @RequestMapping(path = "/register", method = RequestMethod.POST)
    @ResponseBody
    public BaseJSONResult registerUser(@RequestBody TestUser user) {
        System.out.println(user.toString());
        return BaseJSONResult.ok(user.toString());
    }

    /**
     * 带请求头的请求
     *
     * @RequestHeader 将请求头内容绑定到方法参数上
     */
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    @ResponseBody
    public BaseJSONResult login(@RequestHeader("access_token") String accessToken, @RequestParam("name") String name) {
        TestUser user = new TestUser();
        user.setName(name);
        user.setDecribe("accessToken是：" + accessToken);
        if ("wasd".equals(accessToken)) {
            return BaseJSONResult.ok(user);
        } else {
            return BaseJSONResult.errorTokenMsg("Token错误");
        }
    }


    /**
     * 单个文件上传具体实现方法;
     *
     * @param file
     * @return
     */
//    @RequestMapping("/upload")
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public BaseJSONResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String targetPath = "";
            try {
                System.out.println("name:" + file.getName());
                System.out.println("originalFilename:" + file.getOriginalFilename());
                System.out.println("type:" + file.getContentType());
                System.out.println("size:" + file.getSize());
                String originalFilename = file.getOriginalFilename();
                File targetfile = new File(IMG_HEADER + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")));
                if (!targetfile.exists()) {
                    targetfile.createNewFile();
                }
                targetPath = targetfile.getAbsolutePath();
                file.transferTo(targetfile);
                System.out.println("图片路径是 " + targetfile.getAbsolutePath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败," + e.getMessage());
            }
            return BaseJSONResult.ok("上传成功: " + targetPath);
        } else {
            return BaseJSONResult.errorMsg("上传失败，因为文件是空的.");
        }
    }

    /**
     * 多图片上传
     * HttpServletRequest
     */
    @RequestMapping(path = "/uploadMore", method = RequestMethod.POST)
    @ResponseBody
    public BaseJSONResult uploadMore(HttpServletRequest request) {
        MultipartHttpServletRequest params = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = params.getFiles("file");
        List<String> strs = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String originalFilename = file.getOriginalFilename();
            File targetfile = new File(IMG_FRIEND + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")));
            try {
                file.transferTo(targetfile);
            } catch (IOException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败:" + e.getMessage());
            }
            System.out.println("上传成功：" + i + ":" + targetfile.getAbsolutePath());
            strs.add("上传成功：" + i + ":" + targetfile.getAbsolutePath());
        }
        return BaseJSONResult.ok(strs.toString());
    }
}
